package com.qjj.studydainty.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.qjj.studydainty.R;
import com.qjj.studydainty.adapter.FileInfoAdapter;
import com.qjj.studydainty.entity.MyApplication;
import com.qjj.studydainty.entity.MyFileInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.qjj.studydainty.entity.MyApplication.PATH;


public class ExplorerActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private List<MyFileInfo> myFileInfoList = new ArrayList<>();
    private FileInfoAdapter fileInfoAdapter;
    private String inputName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme();
        setContentView(R.layout.activity_explorer);

        recyclerView = findViewById(R.id.recycleView_file);

        myFileInfoList = getDownFile();
        fileInfoAdapter = new FileInfoAdapter(this, myFileInfoList, recyclerView);
        recyclerView.setAdapter(fileInfoAdapter);

        recyclerView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("操作");
                getMenuInflater().inflate(R.menu.file, menu);
            }
        });

        fileInfoAdapter.setOnItemClickListener(new FileInfoAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = getOpenFileIntent(myFileInfoList.get(position).getName());
                startActivity(intent);
            }

            @Override
            public void OnItemLongClick(View view, int position) {
            }
        });

        //设置布局管理
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        //recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //设置动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        //设置分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(Objects.requireNonNull(this), DividerItemDecoration.VERTICAL));

    }
    private void setTheme() {
        if (MyApplication.SHOW_THEME_FLAG == MyApplication.SHOW_WHITE_THEME_FLAG) {
            setTheme(R.style.DayTheme);
        } else if (MyApplication.SHOW_THEME_FLAG == MyApplication.SHOW_BLACK_THEME_FLAG) {
            setTheme(R.style.NightTheme);
        }
    }

    public Intent getOpenFileIntent(String downloadFileName) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File fileDir = new File(PATH);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        if (downloadFileName == null) {
            return new Intent();
        }
        File file = new File(PATH, downloadFileName);

        Uri uri;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            uri = Uri.fromFile(file);
        } else {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = FileProvider.getUriForFile(ExplorerActivity.this, getPackageName() + ".provider", file);
        }
        intent.setData(uri);
        return intent;
    }

    public List<MyFileInfo> getDownFile() {
        String path = Environment.getExternalStorageDirectory().getPath() + "/myDownLoad/";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File[] subFile = dir.listFiles();

        for (File f : subFile) {
            if (f.isFile()) {
                String size = "";
                if (f.length() > 1048576) {
                    size = f.length() / 1048576 + "M";
                } else {
                    size = f.length() / 1024 + "k";
                }

                Bitmap bitmap = null;
                String name = f.getName();
                if (null != name && name.length() > 4) {
                    //String s = name.substring(name.length() - 3);
                    if (name.substring(name.length() - 3).equals("apk")) {
                        Drawable drawable = getApkThumbnail(ExplorerActivity.this, f.getPath());
                        if (drawable != null) {
                            bitmap = drawableToBitmap(drawable);
                        }
                    } else if (name.substring(name.length() - 3).equals("mp4")) {
                        bitmap = ThumbnailUtils.createVideoThumbnail(f.getPath(), MediaStore.Images.Thumbnails.MICRO_KIND);
                    } else if (name.substring(name.length() - 3).equals("jpg") || name.substring(name.length() - 3).equals("png")) {
                        bitmap = getImageThumbnail(f.getPath(), 100, 100);
                    } else if (name.substring(name.length() - 3).equals("zip")) {
                        Resources res = getResources();
                        bitmap = BitmapFactory.decodeResource(res, R.drawable.zip);
                    } else if (name.substring(name.length() - 3).equals("rar")) {
                        Resources res = getResources();
                        bitmap = BitmapFactory.decodeResource(res, R.drawable.rar);
                    }
                }

                MyFileInfo downloadFile = new MyFileInfo(f.getName(), size, f.lastModified(), f.getPath(), bitmap);
                myFileInfoList.add(downloadFile);
            }
        }
        return myFileInfoList;
    }

    /**
     * 根据指定的图像路径和大小来获取缩略图
     * 此方法有两点好处：
     * 1. 使用较小的内存空间，第一次获取的bitmap实际上为null，只是为了读取宽度和高度，
     * 第二次读取的bitmap是根据比例压缩过的图像，第三次读取的bitmap是所要的缩略图。
     * 2. 缩略图对于原图像来讲没有拉伸，这里使用了2.2版本的新工具ThumbnailUtils，使
     * 用这个工具生成的图像不会被拉伸。
     *
     * @param imagePath 图像的路径
     * @param width     指定输出图像的宽度
     * @param height    指定输出图像的高度
     * @return 生成的缩略图
     */
    private Bitmap getImageThumbnail(String imagePath, int width, int height) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高，注意此处的bitmap为null
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        options.inJustDecodeBounds = false; // 设为 false
        // 计算缩放比
        int h = options.outHeight;
        int w = options.outWidth;
        int beWidth = w / width;
        int beHeight = h / height;
        int be = 1;
        if (beWidth < beHeight) {
            be = beWidth;
        } else {
            be = beHeight;
        }
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;
        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        // 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }

    /**
     * Drawable转Bitmap
     *
     * @param drawable
     * @return
     */
    public Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable == null) {
            return null;
        }

        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        //建立对应的Bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);

        return bitmap;
    }

    /**
     * 获取Apk文件的Log图标
     *
     * @param context
     * @param apk_path Apk路径
     * @return
     */
    public Drawable getApkThumbnail(Context context, String apk_path) {
        if (context == null) {
            return null;
        }
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo packageInfo = pm.getPackageArchiveInfo(apk_path, PackageManager.GET_ACTIVITIES);
            ApplicationInfo appInfo = packageInfo.applicationInfo;
            /**获取apk的图标 */
            appInfo.sourceDir = apk_path;
            appInfo.publicSourceDir = apk_path;
            if (appInfo != null) {
                Drawable apk_icon = appInfo.loadIcon(pm);
                return apk_icon;
            }
        } catch (Exception e) {

        }

        return null;
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        int position = fileInfoAdapter.getPosition();
        switch (item.getItemId()) {
            case R.id.open2:
                Intent intent = getOpenFileIntent(myFileInfoList.get(position).getName());
                startActivity(intent);
                break;
            case R.id.update2:
                changeName(position);
                break;
            case R.id.delete2:
                File file = new File(myFileInfoList.get(position).getPath());
                boolean b = file.delete();
                if (b) {
                    Toast.makeText(ExplorerActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(ExplorerActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
                }
                myFileInfoList.clear();
                myFileInfoList = getDownFile();
                fileInfoAdapter.notifyDataSetChanged();
                break;
            case R.id.delete_all2:
                int success = 0;
                int failed = 0;
                for (MyFileInfo m : myFileInfoList) {
                    file = new File(m.getPath());
                    boolean b1 = file.delete();
                    if (b1) {
                        success++;
                    } else {
                        failed++;
                    }
                }

                Toast.makeText(ExplorerActivity.this, "成功删除" + success + "个文件" + "删除失败" + failed + "个文件", Toast.LENGTH_SHORT).show();

                myFileInfoList.clear();
                myFileInfoList = getDownFile();
                fileInfoAdapter.notifyDataSetChanged();


                break;
            default:
                return false;
        }
        return true;
    }

    private void changeName(final int position) {

        View view = View.inflate(ExplorerActivity.this, R.layout.change_name_dialog, null);
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setOutsideTouchable(true);

        View viewParent = View.inflate(ExplorerActivity.this, R.layout.activity_explorer, null);
        popupWindow.showAtLocation(viewParent, Gravity.CENTER, 0, 0);

        final EditText editTextInputName = view.findViewById(R.id.editText_changename);
        final Button buttonOK = view.findViewById(R.id.button_confirm);
        final Button buttonCancel = view.findViewById(R.id.button_back);

        buttonOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = new File(myFileInfoList.get(position).getPath());
                String name = file.getName();
                String path = file.getPath();

                inputName = editTextInputName.getText().toString();

                if (inputName.length() <= 0) {
                    Toast.makeText(ExplorerActivity.this, "不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                String str = path.substring(path.lastIndexOf("."));
                //重命名文件
                String s = path.replace(name, inputName + str);
                file.renameTo(new File(s));
                popupWindow.dismiss();

                myFileInfoList.clear();
                myFileInfoList = getDownFile();
                fileInfoAdapter.notifyDataSetChanged();
            }
        });
        buttonCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });


    }

}
